﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ASMS.Excel2DbTool.Utils
{
    /// <summary>
    /// 仓库数据仓库
    /// </summary>
    public class 仓库数据仓库
    {
        public static void Run(string filePath, string destFileName)
        {
            DataTable dataTable = Sunboxsoft.Excel.ReadTool.ReadExcel(filePath, true);

            StringBuilder geoBuilder = new StringBuilder();

            for (int index = 0; index < dataTable.Rows.Count; index++)
            {
                string nameString = Convert.ToString(dataTable.Rows[index][2]).Trim();
                string geoString = Convert.ToString(dataTable.Rows[index][4]).Trim();
                string valueString = Convert.ToString(dataTable.Rows[index][7]).Trim();

                if (string.IsNullOrEmpty(nameString)
                    || string.IsNullOrEmpty(valueString)
                    || string.IsNullOrEmpty(geoString))
                    continue;

                decimal value = 0;
                if (!decimal.TryParse(valueString, out value))
                {
                    continue;
                }

                string[] geoArr = geoString.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                if (geoArr.Length != 2)
                {
                    continue;
                }


                decimal geoLng = 0;
                decimal geoLat = 0;
                if (!decimal.TryParse(geoArr[0], out geoLng) || !decimal.TryParse(geoArr[1], out geoLat))
                {
                    continue;
                }
                if (geoBuilder.Length == 0)
                {
                    geoBuilder.AppendFormat("{{\"name\":\"{0}\",\"value\":[{1},{2},{3}]}}", nameString, geoArr[0], geoArr[1], value);
                }
                else
                {
                    geoBuilder.AppendFormat(",{{\"name\":\"{0}\",\"value\":[{1},{2},{3}]}}", nameString, geoArr[0], geoArr[1], value);
                }

            }


            StringBuilder builder = new StringBuilder();
            builder.AppendFormat("{{\"mapData\":[{0}]}}", geoBuilder);

            string destFilePath = string.Format("{0}\\{1}", AppDomain.CurrentDomain.BaseDirectory, destFileName);
            System.IO.File.WriteAllText(destFilePath, builder.ToString());
            Console.WriteLine(string.Format("转换完毕{0},count:{1}", destFilePath, dataTable.Rows.Count));
        }
    }
}